#!/bin/bash

DIR=$(dirname $(realpath "${BASH_SOURCE[0]}"))
OPTEE_DIR=$DIR/qemu-optee
BUILDROOT_DIR=$DIR/buildroot_dl
LAUNCH_PATH=$OPTEE_DIR/launch_optee.sh

if [ ! -d $OPTEE_DIR ]; then
	mkdir $OPTEE_DIR
fi

if [ ! -d $BUILDROOT_DIR ]; then
	mkdir $BUILDROOT_DIR
fi

if [ ! -x $LAUNCH_PATH ]; then
	cp $DIR/launch_optee.sh $LAUNCH_PATH
	chmod a+x $LAUNCH_PATH
fi

IMAGE=optee 

DOCKER_NAME=$(docker ps --filter "ancestor=$IMAGE" --filter "status=exited" -a --format "{{.Names}}")

if [ ! -z $DOCKER_NAME ]; then
	# restart and attach if exist
	docker start $DOCKER_NAME
	docker attach $DOCKER_NAME
else
	# run otherwise
	export GID=$(id -g)

	docker run -it \
		-e DISPLAY=$DISPLAY \
		--user optee:$GID \
		-v /tmp/.X11-unix:/tmp/.X11-unix \
		-v $OPTEE_DIR:/home/optee/qemu-optee \
		-v $BUILDROOT_DIR:/home/optee/buildroot_dl \
		$IMAGE
fi
